package com.astrob.activitys;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.astrob.NavFrameSDK;
import com.astrob.adapters.CitysAdapter;
import com.astrob.model.HistoryCityFileHandle;
import com.astrob.model.HistroyCityData;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.model.PoiCityData;
import com.astrob.model.SystemSetFileHandle;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.Utils;

import java.util.ArrayList;
import java.util.List;

public class CitySelectActivity extends Activity {
	private TextView mTvCurCity;
	private ListView mListView;
	private CitysAdapter mAdapter = null;
	private AutoCompleteTextView mInput;
	private boolean seachspotcity_ = false;
	private ArrayList<PoiCityData> citylist_;

	private boolean needShowCountry = false; //true－－修改save的城市， false－－仅切换查询的城市。
	TextView mTvCurrentCountry;
	private boolean needShowCarpos = false;

	ArrayList<HistroyCityData> mListHistorycity = new ArrayList<HistroyCityData>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_city_select);
		mTvCurCity = (TextView) findViewById(R.id.title);
		mListView = (ListView) findViewById(R.id.listview);
		mListView.setVerticalScrollBarEnabled(false);
		mInput = (AutoCompleteTextView) findViewById(R.id.search_input);
		mInput.setHint("请输入城市名称...");
		
		mTvCurrentCountry = (TextView) findViewById(R.id.current_country);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String strCity = extras.getString("curCity");
			mTvCurCity.setText(strCity);
	
			seachspotcity_ = extras.getBoolean("seachspotcity", false);
			needShowCountry = extras.getBoolean("showcountry", false);
			needShowCarpos = extras.getBoolean("needShowCarpos", false);
		} else {
			mTvCurCity.setText(Start.getInstance().MapKit().mSelCityName);
		}

		if (needShowCarpos) {
			findViewById(R.id.carposition_btn).setVisibility(View.VISIBLE);
		}

		findViewById(R.id.changecountry_id).setVisibility(View.GONE);

		mInput.setCursorVisible(true);
		mInput.setThreshold(1000);
		mInput.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
										  KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT
						|| actionId == EditorInfo.IME_ACTION_DONE
						|| actionId == EditorInfo.IME_ACTION_GO
						|| actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == 0) {
					onKeyWordChange();
				}
				return false;
			}
		});
		mInput.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				onKeyWordChange();
			}
		});

		mAdapter = new CitysAdapter(this);
		mListView.setAdapter(mAdapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				onSelected(position);

			}
		});

		mBtsearchkey = (Button) findViewById(R.id.searchkey_btn);
		mBtclearkey = (Button) findViewById(R.id.clearkey_btn);
		mBtclearkey.setVisibility(View.GONE);

		final View activityRootView = findViewById(R.id.searchcity_layout);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					private int preHeight = 0;

					@Override
					public void onGlobalLayout() {
						int heightDiff = activityRootView.getRootView()
								.getHeight() - activityRootView.getHeight();
						System.out.println("height differ = " + heightDiff);
						// 在数据相同时，减少发送重复消息。因为实际上在输入法出现时会多次调用这个onGlobalLayout方法。
						if (preHeight == heightDiff) {
							return;
						}
						preHeight = heightDiff;
						if (heightDiff > 100) {
							mBtsearchkey.setVisibility(View.VISIBLE);
							mBtclearkey.setVisibility(View.VISIBLE);
						} else {
							mBtsearchkey.setVisibility(View.GONE);
							mBtclearkey.setVisibility(View.GONE);
						}
					}

				});


		showHistroy();

	}

	public void showHistroy() {
		mListHistorycity = HistoryCityFileHandle.getInstance().getListHistroyCity();
		if (mListHistorycity != null && mListHistorycity.size() > 0) {
			List<NavFrameSDK.POIDescription> historyCityList = new ArrayList<NavFrameSDK.POIDescription>();
			for (HistroyCityData fav : mListHistorycity) {
				NavFrameSDK.POIDescription data = NavFrameSDK.getInstance().new POIDescription();
				data.name = fav.name;
				data.position.lon = fav.lon;
				data.position.lat = fav.lat;
				historyCityList.add(data);
			}
			mAdapter.setCityDatas(historyCityList);
			mAdapter.notifyDataSetChanged();
		}
	}

	public int dip2px(float dpValue) {
		final float scale = getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	protected void onSelected(int position) {
		if (Utils.isFastDoubleClick())
			return;

		if (position < 0 || position >= Start.getInstance().MapKit().mPOIResult.size() ) {
			return;
		}

		String name = Start.getInstance().MapKit().mPOIResult.get(position).name;
		String[] names = name.split("\n");
		if (names.length == 2) {
			name = names[1];
		}

		Start.getInstance().MapKit().mSelCityName = name;
		Start.getInstance().MapKit().mCityPosition = Start.getInstance().MapKit().mPOIResult
				.get(position).position;
		Log.d("THZ",
				"sel city longlat: "
						+ Start.getInstance().MapKit().mCityPosition.lon + ","
						+ Start.getInstance().MapKit().mCityPosition.lat + ": "
						+ Start.getInstance().MapKit().mSelCityName);
		saveSelCity();

		HistroyCityData fav = new HistroyCityData();
		fav.name = name;
		fav.setLl(new LonLat(Start.getInstance().MapKit().mCityPosition.lon, Start.getInstance().MapKit().mCityPosition.lat));
		HistoryCityFileHandle.getInstance().add(fav);

		setResult(Msg.CITY_CHANGED);
		finish();
	}

	private Button mBtsearchkey;
	private Button mBtclearkey;

	public void onBack(View v) {
		finish();
	}

	public void onCarpos(View v) {
		setResult(Msg.SETSEACHCENTER);
		super.finish();
	}

	@Override
	public void finish() {
		super.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	public void finish2() {
		setResult(Msg.TOMAPMANAGER);
		super.finish();
	}

	public void onSearch(View v) {
		searchCitys();
	}

	public void onClearkey(View v) {
		mInput.setText("");
	}

	protected void onKeyWordChange() {
		searchCitys();
	}

	ProgressDialog mPB;
	String keyname_ = "";

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == Msg.SEARCHFINISH) {
				finishedSearch();
			}
		}

	};

	protected void finishedSearch() {
		if (mPB != null) {
			mPB.dismiss();
			mPB = null;
		}

		mListView.setAdapter(mAdapter);
		mAdapter.setCityDatas(Start.getInstance().MapKit().mPOIResult);
		mAdapter.notifyDataSetChanged();

		if (Start.getInstance().MapKit().mPOIResult.size() < 1) {
			Toast.makeText(this, "查询无结果", Toast.LENGTH_SHORT).show();
		}
		isSearching_ = false;
		
		String cityName = mTvCurCity.getText().toString();
		if (cityName.length() < 2 && needShowCountry) {
			Start.getInstance().MapKit().mSelCityName = Start.getInstance().MapKit().mPOIResult
					.get(0).name;
			Start.getInstance().MapKit().mCityPosition = Start.getInstance().MapKit().mPOIResult
					.get(0).position;
			saveSelCity();	
			mTvCurCity.setText(Start.getInstance().MapKit().mSelCityName);
		}

	}

	boolean isSearching_ = false;

	public void searchCitys() {
		if (isSearching_) {
			return;
		}
		InputMethodManager m = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		m.hideSoftInputFromWindow(mInput.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		keyname_ = mInput.getText().toString();
		if (keyname_.length() < 1) {
			showHistroy();
			Toast.makeText(this, "请输入城市关键字！", Toast.LENGTH_SHORT).show();
			return;
		}

		if (mPB != null) {
			mPB.cancel();
			mPB = null;
		}

		mListView.setAdapter(null);

		mPB = ProgressDialog.show(this, "正在查询", "查询中...");
		isSearching_ = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				Start.getInstance().MapKit().queryCitys(keyname_);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(Msg.SEARCHFINISH);
			}
		}).start();
	}

	void saveSelCity() {
		if (!needShowCountry)
			return;

		Start.getInstance().MapKit().mDefaultCityName = Start.getInstance().MapKit().mSelCityName;

		// 查询的城市无需保存，只保存缺省城市
		// 初始化时查询城市为缺省城市
		SharedPreferences sp = getSharedPreferences(
				"CN", Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putString("defaultcityname",
				Start.getInstance().MapKit().mDefaultCityName);
		editor.putFloat("citylon",
				(float) Start.getInstance().MapKit().mCityPosition.lon);
		editor.putFloat("citylat",
				(float) Start.getInstance().MapKit().mCityPosition.lat);
		editor.commit();

		SystemSetFileHandle.getInstance().getSystemSet().previewLon =  sp.getFloat("previewLon",
				(float) Start.getInstance().MapKit().mCityPosition.lon);
		SystemSetFileHandle.getInstance().getSystemSet().previewLat = sp.getFloat("previewLat",
				(float) Start.getInstance().MapKit().mCityPosition.lat);

		// Start.getInstance().setMetroDB(Start.getInstance().mDefaultCityName);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Msg.TOMAPMANAGER) {
			finish2();
			return;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
}
